<?php
namespace app\api\controller\food;

use app\api\controller\food\Controller;
use app\api\model\food\User as UserModel;

/**
 * 用户管理
 */
class User extends Controller
{
    /**
     * 获取当前用户信息
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUserDetail();
        if (!$this->request->isPost()) {
            return $this->renderSuccess(compact('userInfo'));
        }
        // 更新记录
        if ($userInfo->edit($this->request->post())) {
            return $this->renderMsg('更新成功');
        }
        $error = $userInfo->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 微信小程序用户登录
     */
    public function login()
    {
        $model = new UserModel;
        if($user = $model->login($this->request->post())){
            return $this->renderSuccess(compact('user'));
        }
        $error = $model->getError() ?: '登录失败';
        return $this->renderError($error);
    }
    
    /**
     * 自动登录/注册
     */
    public function autoLogin()
    {
        $model = new UserModel;
        if($user = $model->autoLogin($this->request->post())){
            return $this->renderSuccess(compact('user'));
        }
        $error = $model->getError() ?: '登录失败';
        return $this->renderError($error);
    }

    /**
     * 获取用户手机号
     */
    public function getPhoneNumber()
    {
        $userInfo = $this->getUserDetail();
        $model = new UserModel;
        if ($model->getPhoneNumber($this->request->post(),$userInfo)) {
            return $this->renderMsg('登录成功');
        }
        return $this->renderError('手机号获取失败');
    }

    /**
     * 公众号授权登录
     */
    public function auth($code='',$appid='')
    {
        $model = new UserModel;
        if($user = $model->auth($code,$appid)){
            return $this->renderSuccess(compact('user'));
        }
        $error = $model->getError() ?: '登录失败';
        return $this->renderError($error);          
    }

}
